package com.goods.web.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONBuilder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.support.json.JSONUtils;
import com.github.pagehelper.PageInfo;
import com.goods.pojo.StbBean;
import com.goods.service.IStbService;
import com.goods.util.CommonTools;
import com.goods.util.Md5Util;
import com.somtacode.core.base.result.ResponseDataResult;
import com.somtacode.core.utils.CommonUtil;

@RestController
@RequestMapping("/stb")
public class StbController {

	 private static final Logger logger = LoggerFactory.getLogger(StbBean.class);
	@Autowired
	private IStbService stbService;
	
		/**
		 * 新增机顶盒
		 * @param Stb
		 * @return
		 * @throws Exception
		 */
		
		@RequestMapping(value = "/{userid}",method = RequestMethod.POST )
		@ResponseBody
	    public ResponseDataResult addStb(@PathVariable("userid") String userid,@RequestBody String body,
							    		 HttpServletRequest request) throws Exception{
			String key = "#MKsPK2018#";
	        if(CommonUtil.isNullOrEmpty(body)){
	    		return ResponseDataResult.setErrorResponseResult("body不能为空");
	    	}
	        JSONObject object = JSONObject.fromObject(body);
	        int cpspid = object.getInt("cpspid");
	        long utcTimestamp = Long.parseLong(request.getHeader("UTCTimestamp"));
	        String AuthToken = request.getHeader("AuthToken");
	        Long between = Calendar.getInstance().getTimeInMillis()-utcTimestamp ;//获取时间戳的差值
	        String w = getIpAddr(request);//获取当前用户ip
	        if (between > 5*60*1000) {
	        	logger.info(w);
	        	return ResponseDataResult.setErrorResponseResult("非法请求");
			}
	        String auth_token = Md5Util.md5(body+utcTimestamp+key);
	        try {
	    	   if(auth_token.toLowerCase().equals(AuthToken.toLowerCase())){
	    		   StbBean stb = new StbBean();
	    		   stb.setStbid(userid);
	    		   stb.setMacaddress(object.getString("mac"));
	    		   stb.setIpaddress(w);
	    		   stbService.addStb(stb,userid,cpspid);
	    	   }else{
	    		   return ResponseDataResult.setErrorResponseResult("校验不通过");
	    	   }
	       	} catch (Exception e) {
				e.printStackTrace();
	       	}
	        return ResponseDataResult.setResponseResult() ;
	    }
		/**
		 * 获取请求ip
		 * @param request
		 * @return
		 */
		 private static String getIpAddr(HttpServletRequest request) {
		        String ip = request.getHeader("x-forwarded-for");
		        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		            ip = request.getHeader("Proxy-Client-IP");
		        }
		        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		            ip = request.getHeader("WL-Proxy-Client-IP");
		        }
		        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		            ip = request.getHeader("HTTP_CLIENT_IP");
		        }
		        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		        }
		        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		            ip = request.getRemoteAddr();
		                InetAddress inet = null;
		                try {
		                    inet = InetAddress.getLocalHost();
		                    ip = inet.getHostAddress();
		                } catch (UnknownHostException e) {
		                    e.printStackTrace();
		                }
		            }
		        return ip;
		    }

		/**
		 * 删除机顶盒
		 * @param id
		 * @return
		 * @throws Exception
		 */
		
		@RequestMapping(value="/{userid}",method = RequestMethod.DELETE)
		@ResponseBody
	    public ResponseDataResult deleteStb(@PathVariable("userid")String userid,
	    									@RequestBody String body,
								    		HttpServletRequest request) throws Exception{
			String key = "#MKsPK2018#";
	        if(CommonUtil.isNullOrEmpty(body)){
	    		return ResponseDataResult.setErrorResponseResult("body不能为空");
	    	}
	        JSONObject object = JSONObject.fromObject(body);
	        int cpspid = object.getInt("cpspid");
	        long utcTimestamp = Long.parseLong(request.getHeader("UTCTimestamp"));
	        String AuthToken = request.getHeader("AuthToken");
	        Long between = Calendar.getInstance().getTimeInMillis()-utcTimestamp ;//获取时间戳的差值
	        String w = getIpAddr(request);//获取当前用户ip
	        if (between > 5*60*1000) {
	        	logger.info(w);
	        	return ResponseDataResult.setErrorResponseResult("非法请求");
			}
	        String auth_token = Md5Util.md5(body+utcTimestamp+key);
	        try {
	        	if(auth_token.toLowerCase().equals(AuthToken.toLowerCase())){
	        	   StbBean stb = new StbBean();
	        	   stb.setStbid(userid);
	        	   stb.setMacaddress(object.getString("mac"));
	    		   stb.setIpaddress(w);
	    		   stbService.deleteStb(userid,cpspid);
	    	   }
	       	} catch (Exception e) {
				e.printStackTrace();
	       	}
	        return ResponseDataResult.setResponseResult() ;
	    }


		/**
		 * 修改机顶盒
		 * @param Stb
		 * @return
		 * @throws Exception
		 */
		@PostMapping("/updateStb")
		public ResponseDataResult updateStb(StbBean stb,String userid) throws Exception{
			if(CommonUtil.isNullOrEmpty(stb)){
				return ResponseDataResult.setErrorResponseResult("Stb不能为空");
			}
			return stbService.updateStb(stb,userid);
		}
		
		/**
		 * 根据id获取机顶盒
		 * @param id
		 * @return
		 * @throws Exception
		 */
		@GetMapping("/getStb")
	    public ResponseDataResult getStb(String id) throws Exception{
			List<StbBean> stb = null;
			try {
				stb = stbService.getStb(id);
	    		if(CommonUtil.isNullOrEmpty(stb)){
	        		return ResponseDataResult.setErrorResponseResult("Stb不存在，请重新输入");
	        	}
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	return ResponseDataResult.setResponseResult(stb);
	    }
		
		/**
		 * 获取机顶盒列表
		 * @param p
		 * @param size
		 * @param name
		 * @return
		 * @throws Exception
		 */
		@GetMapping("/listStb")
		public List<StbBean> listStb(Integer p,Integer size,String macaddress) throws Exception {
			p = p == null ? 1 : p;
			size = size == null ? 20 :size;
			StbBean stb = new StbBean();
			if(!CommonTools.isNullOrEmpty(macaddress)){
				stb.setMacaddress(macaddress);
			}
			PageInfo<StbBean> page = stbService.listStb(p, size,stb);
			return page.getList();
		}
}
